package com.BookMate.controller;

import com.BookMate.domain.Book;
import com.BookMate.domain.User;
import com.BookMate.service.BookService;
import com.BookMate.service.UserService;
import com.BookMate.utils.MD5;
import com.BookMate.utils.RandomValidateCode;
import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.support.CaptchaType;
import entity.PageResult;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * 用户登录和注销Controller
 */
@Controller
public class UserController {

    @RequestMapping("/captcha")
    public void happyCaptcha(HttpServletRequest request, HttpServletResponse response) {
        //System.out.println("======生成一次验证码======");
        HappyCaptcha.require(request, response).type(CaptchaType.ARITHMETIC).build().finish();
    }


    /*
   用户登录
    */
    @RequestMapping("/login")
    public String login(User user, String captcha, HttpServletRequest request) {
        boolean flag = HappyCaptcha.verification(request, captcha, true);
        if (!flag) {
            request.setAttribute("msg", "验证码错误");
            return "forward:/admin/login.jsp";
        }
        String md5 = MD5.getMD5(user.getPassword());
        user.setPassword(md5);
        HappyCaptcha.remove(request);
        //清理验证码
        try {
            User u = userService.login(user);
            if (u != null) {
                request.getSession().setAttribute("USER_SESSION", u);
                if ("ADMIN".equals(u.getRole()))
                    return "redirect:/admin/main_admin.jsp";
                else
                    return "redirect:/admin/main_user.jsp";
            } else {
                request.setAttribute("msg", "邮箱或密码错误");
                return "forward:/admin/login.jsp";
            }

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return "forward:/admin/login.jsp";
        }
    }

    @RequestMapping("/toMainPage_user")
    public String toMainPage() {
        return "main_user";
    }

    //注入userService
    @Autowired
    private BookService bookService;
    @Autowired
    private UserService userService;

    /*
    注销登录
     */
    //注册
    @RequestMapping("/goregister")
    public String goregister() {
        return "forward:/admin/register.jsp";
    }

    @RequestMapping("/returnlogin")
    public String returnlogin() {
        return "forward:/admin/login.jsp";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            //销毁Session
            session.invalidate();
            return "forward:/admin/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return "forward:/admin/login.jsp";
        }
    }

    /*@ResponseBody*/
    @RequestMapping("/delete")
    public String delete(String id,HttpServletRequest request) {
        try {
            boolean count = userService.deleteUser(id);
            if (!count) {
                request.setAttribute("msg", "注销失败，请归还当前所借书籍");
                return "forward:/admin/login.jsp";
            }
            HttpSession session = request.getSession();
            session.invalidate();
            return "forward:/admin/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "forward:/admin/login.jsp";
        }
    }

    //@ResponseBody
    @RequestMapping("/addUser")
    public String addUser(User user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user1 = (User) session.getAttribute("USER_SESSION");
        try {
            if (!"ADMIN".equals(user.getRole())) user.setRole("USER");
            String md5 = MD5.getMD5(user.getPassword());
            user.setPassword(md5);
            Integer count = userService.addUser(user);
            if (count != 1) {
                request.setAttribute("msg", "注册失败");
            }
            request.setAttribute("msg", "注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "注册失败");
        } finally {
            if (user1==null ) {
                return "forward:/admin/login.jsp";
            } else {
                return "forward:/searchreader";
            }
        }
    }

    @RequestMapping("/searchreader")
    public ModelAndView searchresder(User user, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        PageResult pageResult = userService.search(user, pageNum, pageSize);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("userlist");
        modelAndView.addObject("pageResult", pageResult);
        modelAndView.addObject("search", user);
        modelAndView.addObject("pageNum", pageNum);
        modelAndView.addObject("gourl", request.getRequestURI());
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/banUserid")
    public Result banUserid(String id) {
        try {
            Integer count = userService.banUserid(id);
            if (count != 1) {
                return new Result(false, "确认失败!");
            }
            return new Result(true, "确认成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "确认失败!");
        }
    }

    @ResponseBody
    @RequestMapping("/disbanUserid")
    public Result disbanUserid(String id) {
        try {
            Integer count = userService.disbanUserid(id);
            if (count != 1) {
                return new Result(false, "确认失败!");
            }
            return new Result(true, "确认成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "确认失败!");
        }
    }

    @RequestMapping("/edituser")
    public String edituser(User user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user1 = (User) session.getAttribute("USER_SESSION");
        user.setPassword(MD5.getMD5(user.getPassword()));
        user.setId(user1.getId());
        user.setRole(user1.getRole());
        userService.edit(user);
        session.invalidate();//销毁Session
        request.getSession().setAttribute("USER_SESSION", user);
        return "forward:/admin/usercenter.jsp";
    }
}